from appium.webdriver.common.appiumby import AppiumBy
from base.base_page import BasePage  # 继承基础页面对象
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

class AddressBookPage(BasePage):
    # 页面元素定位
    # 标题
    PAGE_TITLE = (AppiumBy.XPATH, "//android.widget.TextView[@text='地址簿']")
    # tab切换：寄件地址/收件地址
    SENDER_TAB = (AppiumBy.XPATH, "//android.widget.TextView[@text='寄件地址' and @selected='true']")
    RECEIVER_TAB = (AppiumBy.XPATH, "//android.widget.TextView[@text='收件地址']")
    # 搜索框
    SEARCH_BOX = (AppiumBy.XPATH, "//android.widget.EditText[@hint='请输入姓名/地址/手机号/公司名称']")
    # 地址列表项（通用定位，通过文本区分）
    ADDRESS_ITEM = (AppiumBy.XPATH, "//android.widget.LinearLayout[@resource-id='...address_item']")  # 替换实际resource-id
    # 操作按钮：默认地址、删除、复制、编辑
    DEFAULT_RADIO = (AppiumBy.XPATH, ".//android.widget.RadioButton[@text='默认寄件地址']")
    DELETE_BTN = (AppiumBy.XPATH, ".//android.widget.TextView[@text='删除']")
    COPY_BTN = (AppiumBy.XPATH, ".//android.widget.TextView[@text='复制']")
    EDIT_BTN = (AppiumBy.XPATH, ".//android.widget.TextView[@text='编辑']")
    # 底部按钮
    MANAGE_BTN = (AppiumBy.XPATH, "//android.widget.TextView[@text='管理']")
    ADD_ADDRESS_BTN = (AppiumBy.XPATH, "//android.widget.TextView[@text='新增地址']")

    #地址条目
    ADDRESS_LIST = (AppiumBy.XPATH, "//android.widget.LinearLayout[@resource-id='...address_item']")

    # 管理模式元素
    DELETE_CONFIRM_DIALOG = (AppiumBy.XPATH, "//android.widget.TextView[@text='您确认要删除所选地址么']")
    CONFIRM_DELETE_BTN = (AppiumBy.XPATH, "//android.widget.TextView[@text='删除']")
    CANCEL_DELETE_BTN = (AppiumBy.XPATH, "//android.widget.TextView[@text='取消']")
    FINISH_MANAGE_BTN = (AppiumBy.XPATH, "//android.widget.TextView[@text='完成']")
    # 默认地址元素
    DEFAULT_TAG = (AppiumBy.XPATH, ".//android.widget.TextView[@text='默认']")

    # 新增/编辑页元素
    SAVE_BTN = (AppiumBy.XPATH, "//android.widget.TextView[@text='保存']")
    NAME_INPUT = (AppiumBy.XPATH, "//android.widget.EditText[@hint='真实姓名']")
    PHONE_INPUT = (AppiumBy.XPATH, "//android.widget.EditText[@hint='手机号']")
    ADDRESS_INPUT = (AppiumBy.XPATH, "//android.widget.EditText[@hint='详细地址']")


    # ---------------------- 核心操作方法 ----------------------
    def switch_tab(self, tab_type):
        """
        切换寄件/收件地址Tab
        :param tab_type: 'sender'（寄件地址）或 'receiver'（收件地址）
        """
        if tab_type == 'sender':
            self.click(self.SENDER_TAB)
        else:
            self.click(self.RECEIVER_TAB)
        WebDriverWait(self.driver, 3).until(
            EC.visibility_of_element_located(self.ADDRESS_ITEM)
        )

    def search_address(self, keyword):
        """
        搜索地址
        :param keyword: 姓名/手机号/地址关键字
        """
        self.click(self.SEARCH_BOX)
        self.send_keys(self.SEARCH_BOX, keyword)
        # 模拟输入完成（部分App需按回车，或等待搜索结果）
        time.sleep(1)
        WebDriverWait(self.driver, 3).until(
            EC.visibility_of_any_elements_located(self.ADDRESS_ITEM)
        )


    def is_default_address_set(self, address_name):
        """
        验证指定地址是否为默认地址
        :param address_name: 地址名称（如：测试 13751056424）
        :return: True（是默认）/ False（不是默认）
        """
        try:
            # 找到目标地址项
            target_item = WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((AppiumBy.XPATH,
                                                f"//android.widget.TextView[@text='{address_name}']/ancestor::android.widget.LinearLayout[contains(@resource-id, 'address_item')]"))
            )

            # 获取默认地址单选框状态
            default_radio = target_item.find_element(*self.DEFAULT_RADIO)
            return default_radio.is_selected()

        except Exception as e:
            self.logger.error(f"验证默认地址失败: {e}")
            return False

    def get_address_list(self):
        """
        获取当前地址列表
        :return: 地址名称列表
        """
        items = self.find_elements(self.ADDRESS_ITEM)
        return [item.find_element(AppiumBy.XPATH, ".//android.widget.TextView[@resource-id='...name']").text for item in items]  # 替换实际name的resource-id

    def enter_manage_mode(self):
        """进入管理模式"""
        self.click(self.MANAGE_BTN)
        WebDriverWait(self.driver, 3).until(
            EC.visibility_of_element_located(self.FINISH_MANAGE_BTN)
        )

    def exit_manage_mode(self):
        """退出管理模式"""
        self.click(self.FINISH_MANAGE_BTN)
        WebDriverWait(self.driver, 3).until(
            EC.invisibility_of_element_located(self.FINISH_MANAGE_BTN)
        )

    def select_address(self, address_name):
        """选中目标地址（管理模式下）"""
        target_item = self.find_element((AppiumBy.XPATH,
                                         f"//android.widget.TextView[@text='{address_name}']/ancestor::*[contains(@resource-id, 'address_item')]"))
        target_item.find_element(AppiumBy.XPATH, ".//android.widget.RadioButton").click()

    def delete_address(self, address_name):
        """删除地址（含二次确认）"""
        self.enter_manage_mode()
        self.select_address(address_name)
        self.click((AppiumBy.XPATH, "//android.widget.TextView[@text='删除']"))

        # 处理二次确认弹窗
        WebDriverWait(self.driver, 3).until(
            EC.visibility_of_element_located(self.DELETE_CONFIRM_DIALOG)
        )
        self.click(self.CONFIRM_DELETE_BTN)

        # 验证地址消失
        assert not self.is_element_exist((AppiumBy.XPATH, f"//android.widget.TextView[@text='{address_name}']")), \
            "地址删除失败"
        self.exit_manage_mode()

    def set_default_address(self, address_name):
        """设置默认地址（自动处理状态校验）"""
        target_item = self.find_element((AppiumBy.XPATH,
                                         f"//android.widget.TextView[@text='{address_name}']/ancestor::*[contains(@resource-id, 'address_item')]"))
        target_item.find_element(*self.DEFAULT_RADIO).click()

        # 验证默认标签出现
        WebDriverWait(self.driver, 3).until(
            EC.visibility_of_element_located((AppiumBy.XPATH,
                                              f"//android.widget.TextView[@text='{address_name}']/following::android.widget.TextView[@text='默认']"))
        )
        assert self.is_element_exist(self.DEFAULT_TAG, parent=target_item), "默认地址设置失败"

    def add_new_address(self, name, phone, address):
        """新增地址流程"""
        self.click(self.ADD_ADDRESS_BTN)
        WebDriverWait(self.driver, 3).until(
            EC.visibility_of_element_located(self.NAME_INPUT)
        )

        # 填写信息
        self.send_keys(self.NAME_INPUT, name)
        self.send_keys(self.PHONE_INPUT, phone)
        self.send_keys(self.ADDRESS_INPUT, address)
        self.click(self.SAVE_BTN)

        # 验证地址新增成功
        assert self.is_element_exist((AppiumBy.XPATH, f"//android.widget.TextView[@text='{name} {phone}']")), \
            "新增地址失败"

    def edit_address(self, old_name, new_name):
        """编辑地址流程"""
        target_item = self.find_element((AppiumBy.XPATH,
                                         f"//android.widget.TextView[@text='{old_name}']/ancestor::*[contains(@resource-id, 'address_item')]"))
        target_item.find_element(AppiumBy.XPATH, ".//android.widget.TextView[@text='编辑']").click()

        # 修改姓名
        self.send_keys(self.NAME_INPUT, new_name)
        self.click(self.SAVE_BTN)

        # 验证编辑成功
        assert self.is_element_exist((AppiumBy.XPATH, f"//android.widget.TextView[@text='{new_name}']")), \
            "编辑地址失败"

        # ---------------------- 状态校验 ----------------------

    def is_default_address(self, address_name):
        """校验地址是否为默认"""
        target_item = self.find_element((AppiumBy.XPATH,
                                         f"//android.widget.TextView[@text='{address_name}']/ancestor::*[contains(@resource-id, 'address_item')]"))
        return self.is_element_exist(self.DEFAULT_TAG, parent=target_item)